package com.zlsy.secondtime.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Random;

/**
 * @author zhouliang
 * @date 2020/6/19 8:47
 */
public class ThreadMxBeanFindDeadLock implements Runnable {

    private static final Random RANDOM = new Random();

    private ThreadMxBeanFindDeadLockAccount[] account;

    public ThreadMxBeanFindDeadLock(ThreadMxBeanFindDeadLockAccount[] account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            int fromIndex = RANDOM.nextInt(100);
            int toIndex = RANDOM.nextInt(100);
            int amount = RANDOM.nextInt(1000);
            transferMoney(account[fromIndex], account[toIndex], amount);
        }
    }

    private void transferMoney(ThreadMxBeanFindDeadLockAccount from, ThreadMxBeanFindDeadLockAccount to, int amount) {
        synchronized (from) {
            synchronized (to) {
                if (from.balance - amount < 0) {
                    System.err.println("余额不足！");
                }
                from.balance -= amount;
                to.balance += amount;
            }
        }
    }

    static class ThreadMxBeanFindDeadLockAccount {
        private int balance;

        public ThreadMxBeanFindDeadLockAccount(int balance) {
            this.balance = balance;
        }
    }

    public static void main(String[] args) {
        ThreadMxBeanFindDeadLockAccount[] accounts = new ThreadMxBeanFindDeadLockAccount[100];
        for (int i = 0; i < accounts.length; i++) {
            accounts[i] = new ThreadMxBeanFindDeadLockAccount(1000);
        }

        for (int i = 0; i < 20; i++) {
            ThreadMxBeanFindDeadLock r = new ThreadMxBeanFindDeadLock(accounts);
            Thread thread = new Thread(r);
            thread.start();
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        if (deadlockedThreads != null && deadlockedThreads.length > 0) {
            for (int i = 0; i < deadlockedThreads.length; i++) {
                long deadlockedThread = deadlockedThreads[i];
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThread);
                System.out.println("发现死锁了：" + threadInfo.getLockName());
            }
        }
    }
}
